//
//  HotTopicsViewController.m
//  GiftThat
//
//  Created by ChuXiang on 16/1/6.
//  Copyright © 2016年 ChuXiang. All rights reserved.
//

#import "HotTopicsViewController.h"
#import "LJFHotCollectionViewCell.h"
#import "LJFModel.h"
#import "LJFNewHotViewController.h"
#import <MJRefresh.h>
#import "LJFSearchViewController.h"
@interface HotTopicsViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *muArray;
@property (nonatomic,copy) NSString *nextPageUrl;

@property (nonatomic,strong) UIImageView *imageView;


//-------刷新
//tableview方向判断
@property (nonatomic, assign) CGFloat contenty;
@property (nonatomic, strong) UIView *downLoad;
//box
@property (nonatomic, strong) UIImageView *box;
//heart
@property (nonatomic, strong) UIImageView *heart;
//boxarray
@property (nonatomic, strong) NSMutableArray *boxArray;


@end

@implementation HotTopicsViewController


-(void)viewWillAppear:(BOOL)animated{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Color"] isEqualToString:@"BlackColor"]) {
        self.view.backgroundColor = [UIColor colorWithRed:35 / 255.0 green:34 / 255.0 blue:38 / 255.0 alpha:1.0];
        self.collectionView.backgroundColor = [UIColor colorWithRed:35 / 255.0 green:34 / 255.0 blue:38 / 255.0 alpha:1.0];
        [self.collectionView reloadData];
    }else{
        self.collectionView.backgroundColor =  [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1.0];
        self.view.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1.0];
        [self.collectionView reloadData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.navigationItem.backBarButtonItem.tintColor = [UIColor whiteColor];

    self.navigationItem.title = @"热门";

    self.muArray = [NSMutableArray array];
    
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(searchButtonDid)];
    self.navigationItem.rightBarButtonItem = searchItem;
    
    [self getUrl:kHotTopicsURL];
    [self creatCollectionView];

    [self dongHua];
#pragma mark-新的mjrefresh加载动图用法
    
    [self getFrshImage];

    
}




#pragma mark-新的mjrefresh加载动图用法


-(void)dongHua{
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0 , 80, 80)];
    self.imageView.backgroundColor = [UIColor blackColor];
    self.imageView.alpha = 0.5;
    self.imageView.center = CGPointMake(self.view.width / 2, self.view.height / 2 - 80);
    NSMutableArray*muArray = [NSMutableArray array];
    for (int i = 0; i < 15; i++) {
        [muArray addObject:[UIImage imageNamed:[NSString stringWithFormat:@"loading_%d",i]]];
    }
    [self.imageView setAnimationImages:muArray];
    [self.imageView setAnimationDuration:3];
    [self.imageView startAnimating];
    [self.view addSubview:self.imageView];
  
}


-(void)searchButtonDid{
    
    LJFSearchViewController *searchController = [[LJFSearchViewController alloc]init];
    [self.navigationController pushViewController:searchController animated:YES];
}

//网络请求
-(void)getUrl:(NSString *)url{
    if ([url isEqual:[NSNull null]]) {
        [self.collectionView.mj_footer endRefreshing];
    }else{
    [CXNetWorkTool getWithUrl:url parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        
        NSDictionary *dic = result;
        NSDictionary *dic1 = [dic objectForKey:@"data"];
        NSArray *array = [dic1 objectForKey:@"items"];
//        获取下一页的url
        NSDictionary *dic2 = [[NSDictionary alloc]initWithDictionary:[dic1 objectForKey:@"paging"]];
        self.nextPageUrl  = [dic2 objectForKey:@"next_url"];
        
        for (NSDictionary *dic2 in array) {
            LJFModel *hot = [[LJFModel alloc]initWithDictionary:[dic2 objectForKey:@"data"]];

            [self.muArray addObject:hot];
        }
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.imageView stopAnimating];
            [self.imageView removeFromSuperview];
            
        });

        
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    }
}
//collectionview的创建
-(void)creatCollectionView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = CGFLOAT_MIN;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.itemSize = CGSizeMake((self.view.frame.size.width - 10)/2,200);
    
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(5, 0, self.view.frame.size.width - 10, self.view.frame.size.height - 113) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[LJFHotCollectionViewCell class] forCellWithReuseIdentifier:@"NewCollectionViewCell"];
//    collectionview的上拉加载
    
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footDid)];
    
    [self.view addSubview:self.collectionView];
    
    
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    LJFHotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NewCollectionViewCell" forIndexPath:indexPath];
        if (self.muArray.count > indexPath.item) {
        cell.ljfmodel = self.muArray[indexPath.item];
    }
    return cell;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.muArray.count;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    LJFModel *model = [[LJFModel alloc]init];
    if (self.muArray.count > indexPath.item) {
        model = self.muArray[indexPath.item];
        LJFNewHotViewController *new = [[LJFNewHotViewController alloc]init];
        new.ljfmodel = self.muArray[indexPath.item];
        new.urlString = new.ljfmodel.url;
        [self.navigationController pushViewController:new
                                             animated:YES];
    }
}
#pragma mark-下拉刷新的方法
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.contenty = scrollView.contentOffset.y;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //    if (scrollView.contentOffset.y > self.contenty) {
    //        NSLog(@"加载数据");
    //        if (scrollView.contentOffset.y > scrollView.contentSize.height - 700) {
    //            //加载更多数据
    //            if (scrolltimes == 0) {
    //                numOfAll = numOfAll + 20;
    //                [self netWorkingAll:KHomeAll withLimit:@"20" withAd:@"2" withGender:@"1" withOffset:[NSString stringWithFormat:@"%d", numOfAll] withGeneration:@"1"];
    //                scrolltimes = 1;
    //            }
    //        }
    //    }
    if (scrollView.contentOffset.y < 0) {
        self.downLoad.frame = CGRectMake(0, 5, self.view.width, 0 - scrollView.contentOffset.y);
        self.box.frame = CGRectMake((self.view.width - self.view.width / 10) / 2, 0 - scrollView.contentOffset.y - self.view.width / 10 / 1.23, self.view.width / 10, self.view.width / 10 / 1.23);
        self.heart.frame = CGRectMake((self.view.width - self.box.width / 4 * 2) / 2, 0 - scrollView.contentOffset.y - self.view.width / 10 / 1.23, self.box.width / 4 * 2, self.box.height / 4 * 3);
    }
}


#pragma mark -- 下拉刷新
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < -60) {
        [scrollView setContentOffset:CGPointMake(0, -60) animated:YES];
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.3 animations:^{
                [UIView setAnimationDelay:0];
                self.heart.frame = CGRectMake((self.view.width - self.box.width / 4 * 2) / 2, 0 - scrollView.contentOffset.y - self.view.width / 10 / 1.23 - self.box.height / 4 * 3, self.box.width / 4 * 2, self.box.height / 4 * 3);
                self.heart.alpha = 1;
            } completion:^(BOOL finished) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
                    self.heart.alpha = 0;
                });
            }];
        });
        
        [self.box setAnimationImages:self.boxArray];
        [self.box setAnimationDuration:2];
        [self.box setAnimationRepeatCount:1];
        [self.box startAnimating];
        
        [self.muArray removeAllObjects];
        
        [self getUrl:kHotTopicsURL];
        //        [self netWorkingAll:KHomeAll withLimit:@"20" withAd:@"2" withGender:@"1" withOffset:[NSString stringWithFormat:@"%d", 0] withGeneration:@"1"];
    }
    
}
#pragma mark-上拉加载的方法
-(void)footDid{

    [self getUrl:self.nextPageUrl];
    
    
}

#pragma mark - GetRefrshImage
- (void)getFrshImage {
    //    下拉刷新
    self.downLoad = [[UIView alloc] initWithFrame:CGRectZero];
    self.downLoad.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.downLoad];
    [self.view bringSubviewToFront:self.downLoad];
    
    self.boxArray = [NSMutableArray arrayWithCapacity:0];
    self.box = [[UIImageView alloc] initWithFrame:CGRectZero];
    self.box.image = [UIImage imageNamed:@"box_01.png"];
    [self.downLoad addSubview:self.box];
    
    self.heart = [[UIImageView alloc] initWithFrame:CGRectZero];
    self.heart.image = [UIImage imageNamed:@"box_06"];
    self.heart.alpha = 0;
    [self.downLoad addSubview:self.heart];
    
    self.boxArray = [[NSMutableArray alloc] initWithCapacity:0];
    for (int i = 1; i < 6; i++) {
        NSString *str = [[NSString alloc] initWithFormat:@"box_%02d.png", i];
        UIImage *image = [UIImage imageNamed:str];
        [self.boxArray addObject:image];
    }
    for (int i = 0; i < 30; i++) {
        UIImage *image = [UIImage imageNamed:@"box_05.png"];
        [self.boxArray addObject:image];
    }
    for (int i = 4; i > 0; i--) {
        NSString *str = [[NSString alloc] initWithFormat:@"box_%02d.png", i];
        UIImage *image = [UIImage imageNamed:str];
        [self.boxArray addObject:image];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
